package com.xiaobingby.common.utils;

import com.alibaba.excel.ExcelReader;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.metadata.BaseRowModel;
import com.alibaba.excel.metadata.Sheet;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.baomidou.mybatisplus.mapper.BaseMapper;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;

public class ExcelUtil {
    public static <T>  void exporExcel(HttpServletResponse response, List<? extends BaseRowModel> list,String fileName) throws IOException {
        try(OutputStream outputStream = response.getOutputStream()) {
            //添加响应头信息
            response.setHeader("Content-disposition", "attachment; filename=" + fileName + ".xls");
            response.setContentType("application/msexcel;charset=UTF-8");//设置类型
            response.setHeader("Pragma", "No-cache");//设置头
            response.setHeader("Cache-Control", "no-cache");//设置头
            response.setDateHeader("Expires", 0);//设置日期头

            //实例化 ExcelWriter
            ExcelWriter writer = new ExcelWriter(outputStream, ExcelTypeEnum.XLS, true);

            //实例化表单
            Sheet sheet = new Sheet(1, 0, list.get(0).getClass());

            //输出
            writer.write(list, sheet);
            writer.finish();
            outputStream.flush();
        }
    }

    public static void importExcel(MultipartFile file, Class<? extends BaseRowModel> clazz, BaseMapper baseMapper) throws IOException {
        try(InputStream inputStream = file.getInputStream()){
            //实例化实现了AnalysisEventListener接口的类
            ExcelListener listener = new ExcelListener();
            //传入参数
            ExcelReader excelReader = new ExcelReader(inputStream, ExcelTypeEnum.XLS, null, listener);
            //读取信息
            excelReader.read(new Sheet(1, 1, clazz));
            //获取数据
            List<Object> list = listener.getDatas();
            list.stream().forEach(o -> baseMapper.insert(o));

        }
    }

    public static List<?> importExcel(MultipartFile file, Class<? extends BaseRowModel> clazz) throws IOException {
        try(InputStream inputStream = file.getInputStream()){
            //实例化实现了AnalysisEventListener接口的类
            ExcelListener listener = new ExcelListener();
            //传入参数
            ExcelReader excelReader = new ExcelReader(inputStream, ExcelTypeEnum.XLS, null, listener);
            //读取信息
            excelReader.read(new Sheet(1, 1, clazz));
            //获取数据
            return listener.getDatas();
        }
    }
}
